import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { NavigationEntity } from '../../entities/navigation.entity';
import { CreateNavigationDto, UpdateNavigationDto, NavigationResponseDto } from '../../dto/navigation.dto';

/**
 * 导航站点服务
 */
@Injectable()
export class NavigationService {
  constructor(
    @InjectRepository(NavigationEntity)
    private readonly navigationRepository: Repository<NavigationEntity>,
  ) {}

  /**
   * 获取所有导航站点列表
   * @returns 导航站点列表
   */
  async findAll(): Promise<NavigationResponseDto[]> {
    const navigations = await this.navigationRepository.find({
      where: { isActive: true },
      order: { sort: 'DESC', createdAt: 'ASC' },
    });

    return navigations.map(nav => ({
      id: nav.id,
      name: nav.name,
      description: nav.description,
      url: nav.url,
      logo: nav.logo,
    }));
  }

  /**
   * 根据ID获取导航站点
   * @param id 站点ID
   * @returns 导航站点信息
   */
  async findOne(id: number): Promise<NavigationEntity> {
    const navigation = await this.navigationRepository.findOne({
      where: { id },
    });

    if (!navigation) {
      throw new NotFoundException('导航站点不存在');
    }

    return navigation;
  }

  /**
   * 创建导航站点
   * @param createNavigationDto 创建导航站点数据
   * @returns 创建的导航站点
   */
  async create(createNavigationDto: CreateNavigationDto): Promise<NavigationEntity> {
    const navigation = this.navigationRepository.create({
      ...createNavigationDto,
      sort: createNavigationDto.sort ?? 0,
      isActive: createNavigationDto.isActive ?? true,
    });

    return await this.navigationRepository.save(navigation);
  }

  /**
   * 更新导航站点
   * @param id 站点ID
   * @param updateNavigationDto 更新数据
   * @returns 更新后的导航站点
   */
  async update(id: number, updateNavigationDto: UpdateNavigationDto): Promise<NavigationEntity> {
    const navigation = await this.findOne(id);
    
    Object.assign(navigation, updateNavigationDto);
    
    return await this.navigationRepository.save(navigation);
  }

  /**
   * 删除导航站点（软删除）
   * @param id 站点ID
   */
  async remove(id: number): Promise<void> {
    const navigation = await this.findOne(id);
    await this.navigationRepository.softDelete(id);
  }

  /**
   * 切换导航站点启用状态
   * @param id 站点ID
   * @returns 更新后的导航站点
   */
  async toggleActive(id: number): Promise<NavigationEntity> {
    const navigation = await this.findOne(id);
    navigation.isActive = !navigation.isActive;
    return await this.navigationRepository.save(navigation);
  }
}